package com.ztp.lib.server;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Properties;


public class Env {
	
	public static String OS_WINDOWS = "windows";
	public static String OS_LINUXPC = "linux";
	public static String OS_ANDROID = "android";
	public static String SEP		= System.getProperty("file.separator");
	
	private static String HOME		= null;
	private static String DATA_DIR 	= null;
	private static String OS 		= null;
	
	
	
	public static void setDataDir(String dataDir){
		if(DATA_DIR == null){
			DATA_DIR = dataDir + SEP;
		}
	}
	
	public static String getHome(){
		String os = getOS();
		if(os.equals(OS_ANDROID)){
			return "";
		}
		
		String home = System.getProperty("user.dir");
		if(home.matches(".*:.*")){
			home = home.replaceAll("\\\\", "/");
		}
		home = home.charAt(0) + "\\" + home.substring(1, home.length());
		return home;
	}
	
	public static String getOS(){
		if(OS != null){
			return OS;
		}
		String osName = System.getProperty("os.name");
		if(osName.matches(".*Windows.*")){
			OS = OS_WINDOWS;
		}
		else if(osName.equals("Linux")){
			if(System.getProperty("java.vendor").equals("The Android Project")){
				OS = OS_ANDROID;
			}
			else {
				OS = OS_LINUXPC;
			}
		}
		return OS;
	}
	
	public static String getDataDir(){
		if(DATA_DIR!= null){
			return DATA_DIR;
		}
		
		String osName = System.getProperty("os.name");
		if(osName.matches(".*Windows.*")){
			OS = OS_WINDOWS;
			DATA_DIR = "";
		}
		else if(osName.equals("Linux")){
			if(System.getProperty("java.vendor").equals("The Android Project")){
				OS = OS_ANDROID;
				/*try {
					Class<?> androidAppClass = Class.forName("android.app.Application");
					
					Object androidApp = androidAppClass.newInstance();
					Method method = androidAppClass.getMethod("getCacheDir", new Class []{});
					File cacheDir = (File)method.invoke(androidApp);
					DATA_DIR = cacheDir.getAbsolutePath();
					
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (InstantiationException e) {
					e.printStackTrace();
				}*/
				
				
			}
		}
		
		return DATA_DIR;
	}
	
	public static void printSysPrprts(){
		Properties p = System.getProperties();
		String  [] keys = new String [p.keySet().size()];
		p.keySet().toArray(keys);
		
		Arrays.sort(keys);
		
		for(String k : keys){
			System.out.println(k);
			System.out.println("\t" + p.getProperty(k));
		}
	}
	
}
